package com.example.flowermall.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.flowermall.entity.Result;
import com.example.flowermall.entity.Role;
import com.example.flowermall.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author xiaoman
 * @since 2023-06-07
 */
@RestController
@RequestMapping("/role")
public class RoleController {
    @Autowired
    IRoleService roleService;
    @GetMapping("/list")
    public Result getRoleList(@RequestParam(value = "roleName",required = false)String roleName,
                              @RequestParam(value = "pageNo",required = false)Long pageNo,
                              @RequestParam(value = "pageSize",required = false)Long pageSize){
        LambdaQueryWrapper<Role> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.hasLength(roleName),Role::getRoleName,roleName);
        Page<Role> page=new Page<>(pageNo,pageSize);
        roleService.page(page,queryWrapper);
        Map<String,Object> data=new HashMap<>();

        data.put("total",page.getTotal());
        data.put("rows",page.getRecords());
        return Result.success(data);
    }
    @PostMapping
    public Result addRole(@RequestBody Role role){
        roleService.addRole(role);
        return Result.success("添加角色成功");
    }
    @DeleteMapping("/{id}")
    public Result deleteRole(@PathVariable("id")Integer roleId){
        roleService.delete(roleId);
        return Result.success("删除角色成功");
    }
    @GetMapping("/{id}")
    public Result getRoleById(@PathVariable("id")Integer roleId){
        Role role = roleService.select(roleId);
        Result result=Result.success();
        result.put("data",role);
        return result;
    }
    @PutMapping
    public Result updateRole(@RequestBody Role role){
        roleService.updateRole(role);
        return Result.success("修改角色成功");
    }
    @GetMapping("/all")
    public Result getAllRole(){
        List<Role> list = roleService.list();
        Result result=Result.success();
        result.put("data",list);
        return result;
    }

}
